package cn.opopopo.wordexport.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.lang.Assert;
import cn.opopopo.wordexport.mode.DownloadContractFileDTO;
import cn.opopopo.wordexport.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Api(tags = "首页模块")
@RestController
@Slf4j
public class IndexController {

    @ApiImplicitParam(name = "name",value = "姓名",required = true)
    @ApiOperation(value = "向客人问好")
    @GetMapping("/sayHi")
    public ResponseEntity<String> sayHi(@RequestParam(value = "name")String name){
        return ResponseEntity.ok("Hi:"+name);
    }



    @ApiOperation(value = "文档导出")
    @GetMapping("/wordexport")
    @SneakyThrows
    public ResponseEntity<String> wordExport(HttpServletResponse response) {

        XWPFDocument document = new XWPFDocument();

        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Hello, World!");

        run.setTextHighlightColor("blue");

        XWPFTable table = document.createTable(4,4);
        // 添加表格内容

        table.getRow(0).getCell(0).setText("1");
        table.getRow(0).getCell(1).setText("张三");
        table.getRow(0).getCell(2).setText("李四");
        table.getRow(0).getCell(3).setText("王五");
        table.getRow(1).getCell(0).setText("5");
        table.getRow(1).getCell(1).setText("6");
        table.getRow(1).getCell(2).setText("7");
        table.getRow(1).getCell(3).setText("8");
        table.getRow(2).getCell(0).setText("9");
        table.getRow(2).getCell(1).setText("10");
        table.getRow(2).getCell(2).setText("11");
        table.getRow(2).getCell(3).setText("12");
        table.getRow(3).getCell(0).setText("13");
        table.getRow(3).getCell(1).setText("14");
        table.getRow(3).getCell(2).setText("15");
        table.getRow(3).getCell(3).setText("16");

        // 添加图片
        XWPFParagraph imageParagraph = document.createParagraph();
        XWPFRun imageRun = imageParagraph.createRun();



        ClassPathResource resource = new ClassPathResource("staic/57c6-fxpwyhw5134340.jpg");




        imageRun.addPicture(resource.getStream(), Document.PICTURE_TYPE_JPEG, "57c6-fxpwyhw5134340.jpg", Units.toEMU(200), Units.toEMU(200));

        // 设置中文文件名称
        String fileName = URLEncoder.encode(DateUtil.format(DateUtil.date(), DatePattern.CHINESE_DATE_TIME_PATTERN), "UTF-8");
        // 浏览器默认服务器传过去的是html，不是excel文件
        // 设置响应类型:传输内容是流，并支持中文
        response.setContentType("application/octet-stream;charset=UTF-8");
        // 设置响应头信息header，下载时以文件附件下载
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".docx");

        // 输出流对象
        OutputStream outputStream = response.getOutputStream();

        document.write(outputStream);
        outputStream.close();

//        document.

        return ResponseEntity.ok("Hi:");
    }


    @ApiOperation(value = "多文档导出")
    @GetMapping("/manyWordExport")
    @SneakyThrows
    public ResponseEntity<String> manyWordExport(HttpServletResponse response) {

//
//        //存放--服务器上zip文件的目录
//        String directory = "D:\\repository\\"+"XXXX";
//        File directoryFile=new File(directory);
//        if(!directoryFile.isDirectory() && !directoryFile.exists()){
//            directoryFile.mkdirs();
//        }
//        //设置最终输出zip文件的目录+文件名
//        SimpleDateFormat formatter  = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
//        String zipFileName = formatter.format(new Date())+".zip";
//        String strZipPath = directory+"\\"+zipFileName;
//
//        ZipOutputStream zipStream = null;
//        FileInputStream zipSource = null;
//        BufferedInputStream bufferStream = null;
//        File zipFile = new File(strZipPath);
//        try{
//            //构造最终压缩包的输出流
//            zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
//            for (int i = 0; i<paths.length ;i++){
//                //解码获取真实路径与文件名
//                String realFileName = java.net.URLDecoder.decode(names[i],"UTF-8");
//                String realFilePath = java.net.URLDecoder.decode(paths[i],"UTF-8");
//                File file = new File(realFilePath);
//                //TODO:未对文件不存在时进行操作，后期优化。
//                if(file.exists())
//                {
//                    zipSource = new FileInputStream(file);//将需要压缩的文件格式化为输入流
//                    /**
//                     * 压缩条目不是具体独立的文件，而是压缩包文件列表中的列表项，称为条目，就像索引一样这里的name就是文件名,
//                     * 文件名和之前的重复就会导致文件被覆盖
//                     */
//                    ZipEntry zipEntry = new ZipEntry(realFileName);//在压缩目录中文件的名字
//                    zipStream.putNextEntry(zipEntry);//定位该压缩条目位置，开始写入文件到压缩包中
//                    bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
//                    int read = 0;
//                    byte[] buf = new byte[1024 * 10];
//                    while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1)
//                    {
//                        zipStream.write(buf, 0, read);
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            //关闭流
//            try {
//                if(null != bufferStream) bufferStream.close();
//                if(null != zipStream){
//                    zipStream.flush();
//                    zipStream.close();
//                }
//                if(null != zipSource) zipSource.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        //判断系统压缩文件是否存在：true-把该压缩文件通过流输出给客户端后删除该压缩文件  false-未处理
//        if(zipFile.exists()){
//            downImg(response,zipFileName,strZipPath);
//            zipFile.delete();
//        }
//


        return ResponseEntity.ok("Hi:");
    }


    public void download(List<DownloadContractFileDTO> list) {
        File templateFile = FileUtil.createTemplateFile("zip");
        // 创建一个临时目录用于保存文件夹和文件
        Path tempDir = null;
        try {
            tempDir = Files.createTempDirectory("tempDir");
            for (DownloadContractFileDTO downloadContractFile : list) {
                String name = downloadContractFile.getContractName();
                String code = downloadContractFile.getContractCode();
                List<String> urlList = downloadContractFile.getContractFileUrl();
                // 创建以keyName为名称的文件夹
                String fileName = FileUtil.getFileSubstring(name);
                Path folderPath = Files.createDirectory(tempDir.resolve(fileName + "_" + code));
                for (String url : urlList) {
                    // 下载PDF文件并保存到文件夹中
                    FileUtil.downloadFile(url, folderPath.resolve(name).toString());
                }

            }
            // 压缩文件夹
            FileUtil.zipDirectory(tempDir.toString(),templateFile);
            log.info("文件下载、压缩！完成");
        } catch (Exception e) {
            Assert.notNull(true, "下载失败");
            log.error("下载失败==={}", e.getMessage());
        } finally {
            if (tempDir != null) {
                FileUtil.deleteFilesInDirectory(tempDir.toFile());
            }
            log.info("文件删除完成！");
        }
    }



    @GetMapping("/show")
    public String showExportPage(Model model) {
        // 在视图中展示文件选择选项，例如多个复选框或下拉列表
        List<String> fileNames = Arrays.asList("file1.csv", "file2.csv", "file3.csv");
        model.addAttribute("fileNames", fileNames);
        return "exportPage";
    }

    @PostMapping("/generate")
    public void generateExport(@RequestParam("selectedFiles") List<String> selectedFiles, HttpServletResponse response) {
        try {
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=exportedFiles.zip");
            ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());

            for (String fileName : selectedFiles) {
                // 假设您有一个导出单个CSV文件的方法
                byte[] fileContent = exportSingleCSV(fileName);
                ZipEntry zipEntry = new ZipEntry(fileName);
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write(fileContent);
                zipOutputStream.closeEntry();
            }

            zipOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 示例方法：导出单个CSV文件
    private byte[] exportSingleCSV(String fileName) {
        // 此处为示例，您需要编写实际的CSV导出逻辑
        StringBuilder csvData = new StringBuilder();
        csvData.append("Name, Age, Email\n");
        csvData.append("John, 30, john@example.com\n");
        csvData.append("Alice, 28, alice@example.com\n");

        return csvData.toString().getBytes();
    }





}